package easytasks.ui;

import java.util.ArrayList;
import easytasks.data.DataManager;
import easytasks.data.DataSetup;
import easytasks.data.TaskCategory;
import easytasks.main.R;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class ManageTaskCategoriesActivity extends ListActivity 
{
	private ArrayList<TaskCategory> categories;
	
	private DataSetup dataInit;
	private DataManager dataManager;
	
	private ListView listTaskCategories;
	private EditText editAddCategory;
	private ImageButton butAddCategory;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.managetaskcategories);
        
        listTaskCategories = getListView();
        registerForContextMenu(listTaskCategories);

        editAddCategory = (EditText)findViewById(R.id.editManageTaskCategoriesAdd);
        editAddCategory.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s)
			{
				checkRequiredData();
			}
		});
        
        butAddCategory = (ImageButton)findViewById(R.id.butManageTaskCategoriesAdd);
        butAddCategory.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
				TaskCategory newCategory = new TaskCategory(editAddCategory.getText().toString().trim());
					
				if (categories.contains(newCategory))
				{
					Toast.makeText(ManageTaskCategoriesActivity.this, R.string.edittaskcategories_edit_alreadyexists, Toast.LENGTH_LONG).show();
				}
				else
				{
					dataManager.addTaskCategory(newCategory);
					refresh();
				}
			}
        });
        
        checkRequiredData();
        
        dataInit = new DataSetup(this);
        dataManager = new DataManager(dataInit, PreferenceManager.getDefaultSharedPreferences(this));
    }
	
	private void checkRequiredData() 
	{
		butAddCategory.setEnabled(!editAddCategory.getText().toString().trim().equals(""));
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		if (v == listTaskCategories)
		{
			AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
			menu.setHeaderTitle(categories.get(info.position).getName());
			String[] menuItems = getResources().getStringArray(R.array.managetaskcategories_contextmenu);
			for (int i = 0; i < menuItems.length; i++) menu.add(Menu.NONE, i, i, menuItems[i]);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		final TaskCategory oldCategory = categories.get(info.position);
		
		switch(item.getItemId())
		{
			case 0:
				final NewTaskCategoryNameDialog dialogNewCategory = new NewTaskCategoryNameDialog(this, oldCategory);
				dialogNewCategory.setOnOkClickHandler(new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) 
					{
						TaskCategory newCategory = dialogNewCategory.getNewValue();
						
						if (oldCategory.equals(newCategory)) 
						{
							Toast.makeText(ManageTaskCategoriesActivity.this, R.string.edittaskcategories_edit_equals, Toast.LENGTH_LONG).show();
						}
						else if (categories.contains(newCategory))
						{
							Toast.makeText(ManageTaskCategoriesActivity.this, R.string.edittaskcategories_edit_alreadyexists, Toast.LENGTH_LONG).show();
						}
						else
						{
							dataManager.updateTaskCategory(oldCategory, newCategory);							
							refresh();
						}
					}
				});
				
				dialogNewCategory.show();
				break;
			case 1:
				dataManager.removeTaskCategory(oldCategory);
				refresh();
				break;
		}
		
		return true;
	}
	
	@Override
    public void onResume()
    {
    	super.onResume();
    	refresh();
    }
	
	private void refresh() 
    {
		categories = new ArrayList<TaskCategory>(dataManager.getAllTaskCategories());
		
		ArrayList<String> categoryNames = new ArrayList<String>(categories.size());
		for (TaskCategory category : categories) categoryNames.add(category.getName());
		
		setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, categoryNames));
		editAddCategory.setText("");
    }
}
